<template>
    <div id="app">
        <div class="container" :class="{ 'register-mode': isRegisterMode }">
            <!-- 左侧面板 -->
            <div class="left-side">
                <div class="left-content">
                    <img src="@/assets/logo.png" alt="考试系统插图">
                </div>
            </div>

            <!-- 右侧登录面板 -->
            <div class="right-side">
                <div class="login-form">
                    <div class="login-title">网试宝库 || 登录</div>
                    <div class="login-type-switch" :class="{ 'moving': isMoving, 'email-active': isEmailLogin }">
                        <button :class="{ active: !isEmailLogin }" @click="switchLoginType('idcard')">身份证登录</button>
                        <button :class="{ active: isEmailLogin }" @click="switchLoginType('email')">邮箱登录</button>
                    </div>

                    <!-- 身份证登录表单 -->
                    <div v-if="!isEmailLogin">
                        <div class="input-group">
                            <i class="fas fa-id-card input-icon"></i>
                            <input type="text" class="input-field" placeholder="请输入身份证号" v-model="idcardForm.idcard">
                        </div>
                        <div class="input-group">
                            <i class="fas fa-lock input-icon"></i>
                            <input type="password" class="input-field" placeholder="请输入密码"
                                v-model="idcardForm.password">
                        </div>
                        <div class="remember-forgot">
                            <label>
                                <input type="checkbox" v-model="idcardForm.remember"> 记住密码
                            </label>
                            <a href="#">忘记密码？</a>
                        </div>
                        <button class="btn" @click="handleIdcardLogin">登录</button>
                    </div>

                    <!-- 邮箱登录表单 -->
                    <div v-if="isEmailLogin">
                        <div class="input-group">
                            <i class="fas fa-envelope input-icon"></i>
                            <input type="email" class="input-field" placeholder="请输入邮箱" v-model="emailForm.email">
                        </div>
                        <div class="input-group verify-code-group">
                            <i class="fas fa-shield-alt input-icon"></i>
                            <input type="text" class="input-field" placeholder="请输入验证码" v-model="emailForm.code">
                            <button class="verify-code-btn" @click="sendVerifyCode" :disabled="isCountingDown">{{
                                countDownText }}</button>
                        </div>
                        <button class="btn" @click="handleEmailLogin">登录</button>
                    </div>

                    <div class="register-link">
                        还没有账号？<a href="#" @click.prevent="toggleRegister">注册账号</a>
                    </div>
                </div>
            </div>

            <!-- 注册表单 -->
            <div class="register-form" v-if="isRegisterMode">
                <div class="login-title">网试宝库 || 注册</div>
                <div class="register-form-content">
                    <div class="input-group">
                        <i class="fas fa-envelope input-icon"></i>
                        <input type="email" class="input-field" placeholder="请输入邮箱" v-model="registerForm.email">
                    </div>
                    <div class="input-group verify-code-group">
                        <i class="fas fa-shield-alt input-icon"></i>
                        <input type="text" class="input-field" placeholder="请输入验证码" v-model="registerForm.code">
                        <button class="verify-code-btn" @click="sendVerifyCode" :disabled="isCountingDown">{{
                            countDownText }}</button>
                    </div>
                    <div class="input-group">
                        <i class="fas fa-lock input-icon"></i>
                        <input type="password" class="input-field" placeholder="请输入密码" v-model="registerForm.password">
                    </div>
                    <div class="input-group">
                        <i class="fas fa-lock input-icon"></i>
                        <input type="password" class="input-field" placeholder="请确认密码"
                            v-model="registerForm.confirmPassword">
                    </div>
                    <button class="btn" @click="handleRegister">注册</button>
                    <div class="register-link">
                        已有账号？<a href="#" @click.prevent="toggleRegister">返回登录</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import axios from 'axios';

export default {
  data() {
    return {
      isEmailLogin: false,
      isMoving: false,
      isRegisterMode: false,
      isLogin: true,
      isCountingDown: false,
      countdown: 300,
      countDownText: "获取验证码",
      isVcodeDisabled: false,
      buttonText: "获取验证码",
      error: null,
      idcardForm: {
        idcard: "",
        password: "",
        remember: false,
      },
      emailForm: {
        email: "",
        code: "",
      },
      registerForm: {
        email: "",
        password: "",
        confirmPassword: "",
        code: "",
      },
      vcodeExpiration: 5 * 60 * 1000,
      vcodeSentTime: null,
    };
  },
  mounted() {
    const savedIdcard = localStorage.getItem("idcard");
    const savedPassword = localStorage.getItem("password");
    const remember = localStorage.getItem("remember") === "true";

    if (remember && savedIdcard && savedPassword) {
      this.idcardForm.idcard = savedIdcard;
      this.idcardForm.password = savedPassword;
      this.idcardForm.remember = true;
    }
  },
  methods: {
    switchLoginType(type) {
      if (this.isMoving) return;
      this.isMoving = true;
      setTimeout(() => {
        this.isEmailLogin = type === "email";
        setTimeout(() => {
          this.isMoving = false;
        }, 300);
      }, 150);
    },

    // 通用发送验证码请求
    sendVerifyCodeRequest(email) {
      if (this.isVcodeDisabled) return;

      this.isVcodeDisabled = true;
      this.startVcodeCooldown(300);

      axios
        .get(`http://localhost:8080/user/getCode?email=${email}`, { withCredentials: true })
        .then((response) => {
          if (response.data && response.data.code === 0) {
            this.vcodeSentTime = Date.now();
            sessionStorage.setItem("vcodeSentTime", this.vcodeSentTime);
            this.showSuccessMessage("验证码已发送，请查收您的邮箱！");
          } else {
            this.showErrorMessage(response.data.msg || "验证码获取失败，请稍后重试");
          }
        })
        .catch(() => {
          this.showErrorMessage("获取验证码失败，请稍后再试");
        });
    },

    sendVerifyCode() {
      const email = this.isLogin ? this.emailForm.email : this.registerForm.email;
      if (!email) {
        this.showErrorMessage("请输入有效的邮箱！");
        return;
      }

      this.sendVerifyCodeRequest(email);
    },

    showSuccessMessage(message) {
      this.$message.success(message);
    },

    startVcodeCooldown(time) {
      this.countdown = time;
      this.countDownText = `${this.countdown}s 后重试`;

      const timer = setInterval(() => {
        this.countdown--;
        this.countDownText = `${this.countdown}s 后重试`;

        if (this.countdown <= 0) {
          clearInterval(timer);
          this.isVcodeDisabled = false;
          this.countDownText = "获取验证码";
        }
      }, 1000);
    },

    toggleRegister() {
      this.isRegisterMode = !this.isRegisterMode;
      this.isLogin = !this.isLogin;
      const leftSide = document.querySelector(".left-side");
      leftSide.classList.remove("animated", "reverse");

      setTimeout(() => {
        leftSide.classList.add("animated");
        if (this.isRegisterMode) {
          leftSide.classList.add("reverse");
        }
      }, 10);
    },

    handleIdcardLogin() {
      const { idcard, password, remember } = this.idcardForm;
      axios
        .post(
          "http://localhost:8080/user/loginjson",
          { identityCard: idcard, password },
          { withCredentials: true }
        )
        .then((res) => {
          if (res.data === "登录成功") {
            if (remember) {
              localStorage.setItem("idcard", idcard);
              localStorage.setItem("password", password);
              localStorage.setItem("remember", "true");
            } else {
              localStorage.removeItem("idcard");
              localStorage.removeItem("password");
              localStorage.setItem("remember", "false");
            }
            this.$message.success(res.data);
            window.location.href = "../html/index-new.html";
          } else {
            this.$message.error(res.data);
          }
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("登录失败，请稍后再试");
        });
    },

    handleEmailLogin() {
      axios
        .post("http://localhost:8080/user/maillogin", this.emailForm, { withCredentials: true })
        .then((response) => {
          if (response.data === "登录成功") {
            this.$message.success("登录成功，正在跳转...");
            window.location.href = "/dashboard";
          } else {
            this.showErrorMessage(response.data || "登录失败，请稍后再试！");
          }
        })
        .catch(() => {
          this.showErrorMessage("登录失败，请稍后再试！");
        });
    },

    handleRegister() {
      const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/;
      const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;

      if (!emailRegex.test(this.registerForm.email)) {
        this.$message.error("邮箱格式不正确");
        return;
      }
      if (!passwordRegex.test(this.registerForm.password)) {
        this.$message.error("密码必须至少 6 位，并包含至少一个字母和一个数字");
        return;
      }
      if (this.registerForm.password !== this.registerForm.confirmPassword) {
        this.$message.error("两次密码不一致");
        return;
      }
      if (!this.registerForm.code) {
        this.$message.error("请输入验证码");
      }

      const payload = {
        email: this.registerForm.email,
        password: this.registerForm.password,
        code: this.registerForm.code,
      };

      axios
        .post("http://localhost:8080/user/studentregisterjson", payload)
        .then((res) => {
          if (res.data.message === "注册成功") {
            this.$message.success(res.data.message);
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch((error) => {
          console.error(error.response || error);
          const errorMessage = error.response && error.response.data ? error.response.data.message : "注册失败，请稍后再试";
          this.$message.error(errorMessage);
        });
    },

    showErrorMessage(message) {
      this.$message.error(message);
    },
  },
};
</script>


<style>
@import '@/assets/css/keyframes.css';

:root {
    --form-width: 320px;
    --input-height: 45px;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Arial', sans-serif;
    background: url(../assets/图片6.jpg) no-repeat center center fixed;
    background-size: cover;
    backdrop-filter: blur(7px);
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}

.container {
    background-color: white;
    border-radius: 20px;
    box-shadow: 0 0px 15px rgba(0, 0, 0, 0.1);
    position: relative;
    overflow: hidden;
    width: 900px;
    max-width: 100%;
    min-height: 500px;
    display: flex;
}

/* 左侧面板样式 */
.left-side {
    flex: 1;
    padding: 40px;
    background: linear-gradient(to left, #ffffff, #dfdff6, #b7c2ee, #85a8e6, #3490de);
    color: white;
    display: flex;
    flex-direction: column;
    position: absolute;
    width: 50%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 2;
    border-radius: 20px;
    transition: transform 0.6s ease-in-out;
}

.animated {
    animation: a 0.6s linear forwards;
}

.reverse {
    /* animation-direction: reverse; */
    animation: b 0.6s linear forwards;
}

.container.register-mode .left-side {
    transform: translateX(100%);
}

.logo {
    font-size: 24px;
    margin-bottom: 20px;
}

.left-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
}

.left-content h1 {
    margin-bottom: 30px;
    font-size: 32px;
}

.left-content img {
    width: 100%;
    max-width: 300px;
}

/* 右侧面板样式 */
.right-side {
    position: absolute;
    width: 50%;
    height: 100%;
    top: 0;
    left: 50%;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px;
    z-index: 1;
    transition: transform 0.6s ease-in-out;
    padding-top: 70px;
}

.container.register-mode .right-side {
    transform: translateX(-100%);
}

/* 登录表单样式 */
.login-form {
    width: 100%;
    max-width: var(--form-width);
    transition: all 0.6s ease-in-out;
    opacity: 1;
    position: relative;
    min-height: 400px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.container.register-mode .login-form {
    opacity: 0;
    transform: translateX(-30px);
    pointer-events: none;
}

.login-title {
    font-size: 24px;
    color: #333;
    margin-bottom: 30px;
    text-align: center;
    font-weight: bold;
}

/* 登录方式切换样式 */
.login-type-switch {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
    gap: 20px;
    position: relative;
}

.login-type-switch::after {
    content: '';
    position: absolute;
    bottom: -2px;
    left: 0;
    width: 85px;
    height: 2px;
    background: #3490de;
    transition: transform 0.3s ease;
}

.login-type-switch button {
    background: none;
    border: none;
    color: #666;
    cursor: pointer;
    padding: 5px 10px;
    font-size: 14px;
}

.login-type-switch button:hover {
    color: #3490de;
    transition: color 0.3s ease;
}

.login-type-switch button.active {
    color: #3490de;
}

.login-type-switch.email-active::after {
    transform: translateX(105px);
}

.login-type-switch.moving::after {
    background: linear-gradient(90deg,
            #3490de 0%,
            #3490de 50%,
            transparent 50%,
            transparent 100%);
    background-size: 200% 100%;
    animation: moveWave 0.3s linear;
}

@keyframes moveWave {
    0% {
        width: 85px;
        background-position: 100% 0;
    }

    50% {
        width: 190px;
        background-position: 50% 0;
    }

    100% {
        width: 85px;
        background-position: 0 0;
    }
}

/* 输入框组样式 */
.input-group {
    position: relative;
    margin-bottom: 25px;
    width: 100%;
}

.input-field {
    width: 100%;
    height: var(--input-height);
    padding-left: 40px;
    border: 1px solid #ddd;
    border-radius: 22px;
    font-size: 14px;
    transition: all 0.3s ease;
}

.input-icon {
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    color: #666;
    transition: all 0.3s ease;
}

.input-field:focus {
    border-color: #3490de;
    box-shadow: 0 0 0 3px rgba(72, 201, 163, 0.1);
    outline: none;
}

.input-field:focus+.input-icon {
    color: #3490de;
}

.input-field:hover {
    border-color: #3490de;
}

/* 验证码按钮样式 */
.verify-code-group .input-field {
    padding-right: 130px;
}

.verify-code-btn {
    position: absolute;
    right: 5px;
    top: 50%;
    transform: translateY(-50%);
    height: calc(var(--input-height) - 10px);
    padding: 0 20px;
    border: none;
    background: #3490de;
    color: white;
    border-radius: 22px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s ease;
}

.verify-code-btn:hover {
    background: #355c7d;
}

.verify-code-btn:active {
    transform: translateY(-50%) scale(0.98);
}

.verify-code-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

/* 记住密码样式 */
.remember-forgot {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    font-size: 14px;
    line-height: 1;
}

.remember-forgot label {
    display: inline-flex;
    align-items: center;
    color: #666;
    cursor: pointer;
    gap: 5px;
    height: 14px;
    line-height: 14px;
}

.remember-forgot input[type="checkbox"] {
    margin: 0;
    cursor: pointer;
    width: 14px;
    height: 14px;
    vertical-align: top;
    position: relative;
    border: 1px solid #ddd;
    border-radius: 3px;
    transition: all 0.3s ease;
    appearance: none;
    -webkit-appearance: none;
}

.remember-forgot input[type="checkbox"]:checked {
    background: #3490de;
    border-color: #3490de;
}

.remember-forgot input[type="checkbox"]:checked::after {
    content: '✓';
    position: absolute;
    color: white;
    font-size: 12px;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

.remember-forgot a {
    color: #3490de;
    text-decoration: none;
    line-height: 14px;
    height: 14px;
    display: inline-block;
}

/* 按钮样式 */
.btn {
    width: 100%;
    height: var(--input-height);
    border: none;
    background: #3490de;
    color: white;
    font-size: 16px;
    border-radius: 22px;
    cursor: pointer;
    transition: background 0.3s;
}

#idcard-login .btn {
    margin-top: 0;
}

#email-login .btn {
    margin-top: 20px;
}

/* 登录表单切换样式 */
#idcard-login,
#email-login {
    transition: all 0.3s ease-in-out;
    opacity: 1;
    transform: translateX(0);
    position: absolute;
    width: 100%;
    left: 0;
    top: 120px;
    pointer-events: none;
}

#idcard-login {
    pointer-events: auto;
}

#email-login {
    transition: all 0.3s ease-in-out;
    opacity: 0;
    transform: translateX(20px);
    position: absolute;
    width: 100%;
    left: 0;
    top: 120px;
    pointer-events: none;
}

#email-login.active {
    opacity: 1;
    transform: translateX(0);
    pointer-events: auto;
}

#idcard-login.hide {
    opacity: 0;
    transform: translateX(-20px);
    pointer-events: none;
}

#email-login.hide {
    opacity: 0;
    transform: translateX(20px);
    pointer-events: none;
}

/* 修改注册表单样式 */
.register-form {
    position: absolute;
    width: 50%;
    height: 100%;
    top: 0;
    left: 0;
    background: white;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40px;
    z-index: 1;
    opacity: 0;
    transition: all 0.6s ease-in-out;
    transform: translateX(100%);
    pointer-events: none;
}

/* 添加注册表单内容容器 */
.register-form-content {
    width: 100%;
    max-width: var(--form-width);
    min-height: 400px;
    /* 与登录表单一致 */
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* 修改注册表单标题位置 */
.register-form .login-title {
    width: 100%;
    max-width: var(--form-width);
    text-align: center;
    margin-bottom: 40px;
}

.container.register-mode .register-form {
    transform: translateX(0);
    opacity: 1;
    pointer-events: auto;
}

/* 修改注册表单内容的宽度限制 */
.register-form .input-group,
.register-form .btn {
    width: 100%;
    max-width: var(--form-width);
}

.register-link {
    margin-top: 20px;
    text-align: center;
    width: 100%;
    font-size: 14px;
    color: #666;
    position: absolute;
    bottom: 25px;
}

.register-link a {
    color: #3490de;
    text-decoration: none;
    font-weight: bold;
}

/* 页脚样式
.footer {
    position: fixed;
    bottom: 20px;
    text-align: center;
    color: white;
    font-size: 12px;
    left: 50%;
    transform: translateX(-50%);
} */
</style>